package com.qbccn.oauth2service.config;

import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义token生成策略
 */
public class CustomTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken,
                                     OAuth2Authentication authentication) {
        if (accessToken instanceof DefaultOAuth2AccessToken) {
            DefaultOAuth2AccessToken token = ((DefaultOAuth2AccessToken) accessToken);
            //自定义自己的 access_token
            token.setValue(customToken());
            OAuth2RefreshToken refreshToken = token.getRefreshToken();
            if (refreshToken instanceof DefaultOAuth2RefreshToken) {
                //自定义生成的 refreshToken
                token.setRefreshToken(new DefaultOAuth2RefreshToken(customRefreshToken()));
            }
            Map<String, Object> additionalInformation = new HashMap<>();
            additionalInformation.put("client_id", authentication.getOAuth2Request().getClientId());
            token.setAdditionalInformation(additionalInformation);
            return token;
        }
        return accessToken;
    }

    private static int i = 0;
    private static int j = 0;

    /**
     * 自定义token的值
     * 集群的时候注意不要生成重复的值即可
     */
    private String customToken() {
        i = i + 1;
        return "666" + i;
    }

    /**
     * 自定义token的值
     * 集群的时候注意不要生成重复的值即可
     */
    private String customRefreshToken() {
        j = j + 1;
        return "888" + i;
    }
}
